/**
 * 
 */
package com.oet.service.manager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;


import com.oet.utility.RandomString;


/**
 * @author y140zhan
 *
 */
public class BackupManager {
	
	private final static Logger logger = Logger.getLogger(BackupManager.class.getName());
	
	protected static String backupCommand;
	
	protected static String restoreCommand;
	
	
	/**
	 * @return the basePath
	 */
	public String getBackupCommand() {
		return backupCommand;
	}

	/**
	 * @param basePath the basePath to set
	 */
	public  void setBackupCommand(String backupCommand) {
		BackupManager.backupCommand = backupCommand;
	}
	
	/**
	 * @return the basePath
	 */
	public String getRestoreCommand() {
		return restoreCommand;
	}

	/**
	 * @param basePath the basePath to set
	 */
	public  void setRestoreCommand(String restoreCommand) {
		BackupManager.restoreCommand = restoreCommand;
	}
	
	public static String backupDb()
	{
		try {
            Runtime runtime = Runtime.getRuntime();
            String backupFilePath = FileManager.getPath(FileManager.FILE_KEY_BACKUP);
            Date now = new Date();
            String rand = RandomString.getRandomString(3);
            String backupFileName = backupFilePath + now.getYear() 
            + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds()
            + "_" + rand + ".sql";
            
            
            String backupErrorLogName = backupFilePath + now.getYear() 
            + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds()
             + "_" + rand + ".errorLog";
            
            File backupFile = FileManager.createFileByName(backupFileName);
            File backupFileErrorLog = FileManager.createFileByName(backupErrorLogName);

            //"mysqldump --default-character-set=utf-8 --extended-insert=flase --hex-blob -uroot -p000000 --opt --single-transaction ydk"
            Process proc = runtime.exec(backupCommand);
            
            OutputStreamWriter ow = new OutputStreamWriter(proc.getOutputStream(), "utf-8");
            BufferedWriter bw = new BufferedWriter(ow);
         // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERROR", backupFileErrorLog);            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUTPUT", backupFile);
            
            
            errorGobbler.start();
            outputGobbler.start();
            
            
            try {
				int exitVal = proc.waitFor();
				logger.warn("ExitValue: " + exitVal);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				
			}
			
			return backupFileName;
            
            
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
        
	}
	
	public static String restoreDb(byte[] restoreFile)
	{
		
		OutputStreamWriter ow = null;
		BufferedReader br = null;
		OutputStream out = null; 
		try {
            Runtime runtime = Runtime.getRuntime();
            String backupFilePath = FileManager.getPath(FileManager.FILE_KEY_BACKUP);
            Date now = new Date();
            String rand = RandomString.getRandomString(3);
            String backupFileName = backupFilePath + now.getYear() 
            + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds()
            + "_" + rand + ".rsLog";
            
            String backupErrorLogName = backupFilePath + now.getYear() 
            + now.getMonth() + now.getDay() + now.getHours() + now.getMinutes() + now.getSeconds()
             + "_" + rand + ".eRsLog";
            
            File backupFile = FileManager.createFileByName(backupFileName);
            File backupFileErrorLog = FileManager.createFileByName(backupErrorLogName);
            


            //"mysqldump --default-character-set=utf-8 --extended-insert=flase --hex-blob -uroot -p000000 --opt --single-transaction ydk"
            Process proc = runtime.exec(restoreCommand);
            
//            br = new BufferedReader(
//            		new InputStreamReader(new ByteArrayInputStream(restoreFile), "utf-8"));
            out =  proc.getOutputStream();
            out.write(restoreFile);
//            ow = new OutputStreamWriter(out, "utf-8");
            
//            ow.write(br.read());
//            ow.flush();
//            proc.getOutputStream().write(restoreFile);
         // any error message?
            StreamGobbler errorGobbler = new 
                StreamGobbler(proc.getErrorStream(), "ERROR", backupFileErrorLog);            
            
            // any output?
            StreamGobbler outputGobbler = new 
                StreamGobbler(proc.getInputStream(), "OUTPUT", backupFile);
            
            
            errorGobbler.start();
            outputGobbler.start();
            
            
//            try {
////				int exitVal = proc.waitFor();
////				logger.warn("ExitValue: " + exitVal);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			
            
            
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        finally
		{
			if (ow != null)
			{
				try {
					ow.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (br != null)
			{
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (out != null)
			{
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
        return null;
        
	}


	

}
